package com.yonyou.cyxdms.sysAuth.service.service.manage.company;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoleilu.hutool.util.StrUtil;
import com.yonyou.cloud.http.plus.domain.MessEvent;
import com.yonyou.cloud.http.plus.remote.IRemoteInvoke;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.bean.BeanMapperUtil;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.StringUtil;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthCommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.ComOrganizationDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.*;
import com.yonyou.cyxdms.sysAuth.service.entity.role.RolePO;
import com.yonyou.cyxdms.sysAuth.service.feign.IAuthProviderService;
import com.yonyou.cyxdms.sysAuth.service.mapper.*;
import com.yonyou.cyxdms.sysAuth.service.service.EmpService;
import com.yonyou.cyxdms.sysAuth.service.service.Login.UserLoginService;
import com.yonyou.cyxdms.sysAuth.service.service.UserService;
import com.yonyou.cyxdms.sysAuth.service.service.dealerchannel.DealerInfoService;
import com.yonyou.cyxdms.sysAuth.service.service.jwt.JwtService;
import com.yonyou.cyxdms.sysAuth.service.service.manage.asc.AscInfoService;
import com.yonyou.cyxdms.sysAuth.service.service.org.OrgService;
import com.yonyou.cyxdms.sysAuth.service.utill.BeanUtils;
import com.yonyou.cyxdms.sysAuth.service.utill.MD5Util;
import com.yonyou.cyxdms.sysAuth.service.vo.companyorg.CompanyOrgMaintenanceTreeVO;
import com.yonyou.cyxdms.sysAuth.service.vo.companyorg.CompanyOrgPageVO;
import com.yonyou.cyxdms.sysAuth.service.vo.companyorg.MergeVO;
import com.yonyou.cyxdms.sysmanage.client.constants.BaseDataDictConstants;
import com.yonyou.cyxdms.sysmanage.client.vo.asc.AscInfoVO;
import com.yonyou.cyxdms.sysmanage.client.vo.company.CompanyDealerAscVO;
import com.yonyou.cyxdms.sysmanage.client.vo.company.CompanyVO;
import com.yonyou.cyxdms.sysmanage.client.vo.dealer.DealerInfoVO;
import com.yonyou.cyxdms.sysmanage.client.vo.employee.LoginUserVO;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 公司组织维护
 *
 * @author renwd
 * @since 2019/7/8
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class CompanyOrgMaintenanceServiceImpl extends ServiceImpl<ComOrganizationMapper, ComOrganizationPO> implements CompanyOrgMaintenanceService {

    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(CompanyOrgMaintenanceServiceImpl.class);
    @Autowired
    private IAuthProviderService authProviderService;
    @Autowired
    private ComOrganizationMapper organizationMapper;
    @Autowired
    private TrOrgMapper trOrgMapper;
    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private IRemoteInvoke iRemoteInvoke;

    @Autowired
    private DealerInfoService dealerInfoService;
    @Autowired
    private DealerInfoMapper dealerInfoMapper;
    @Autowired
    private AscInfoMapper ascInfoMapper;
    @Autowired
    private AscInfoService ascInfoService;

    @Autowired
    private OrgService orgService;

    @Autowired
    private EmpService empService;

    @Autowired
    private UserService userService;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private PermissionMenuMapper permissionMenuMapper;

    @Autowired
    private PermissionMenuActionMapper permissionMenuActionMapper;

    @Autowired
    private PermissionMenuRangeMapper permissionMenuRangeMapper;

    @Autowired
    private MenuRangeMapper menuRangeMapper;

    @Autowired
    private MenuActionMapper menuActionMapper;

    @Autowired
    private UserOrgMapper userOrgMapper;

    @Autowired
    private OrgRoleMapper orgRoleMapper;

    @Autowired
    private RolePositionMapper rolePositionMapper;

    /*    @Autowired
        private OrgPositionMapper orgPositionMapper;

        @Autowired
        private UserOrgPositionMapper userOrgPositionMapper;

        @Autowired
        private OrgPositionRoleMapper orgPositionRoleMapper;*/
    @Autowired
    public RedissonClient redissonClient;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private JwtService jwtService;

    /**
     * 分页查询公司组织
     *
     * @param page
     * @param queryCondition
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.yonyou.cyxdms.sysAuth.service.vo.companyorg.CompanyOrgPageVO>
     * @author renwd
     * @since 2019/7/8
     */
    @Transactional(readOnly = true)
    @Override

    public IPage<CompanyOrgPageVO> pageCompanyOrg(Page page, Map<String, Object> queryCondition) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        queryCondition.put("appId", loginInfoDto.getAppId());
        queryCondition.put("dealerCode", loginInfoDto.getOwnerCode());
        logger.debug("queryCondition:{}", queryCondition);
        List<CompanyOrgPageVO> voList = organizationMapper.pageComOrganization(page, queryCondition);
        page.setRecords(voList);
        return page;
    }

    /**
     * 获取公司组织树
     *
     * @return java.util.List<java.util.Map>
     * @author renwd
     * @since 2019/7/8
     */
    @Transactional(readOnly = true)
    @Override
    public List<CompanyOrgMaintenanceTreeVO> getComOrgTree() throws ServiceBizException {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<CompanyOrgMaintenanceTreeVO> comOrgTree = organizationMapper.getComOrgTree(loginInfoDto.getAppId(), loginInfoDto.getCompanyId());

        comOrgTree.stream().forEach(orgTree -> {
            if (StringUtils.isNullOrEmpty(orgTree.getParentOrgId())) {
                orgTree.setParent("#");
            }
        });
        return comOrgTree;
    }

    /**
     * 获取部门组织树
     *
     * @return java.util.List<java.util.Map>
     * @author wst
     * @since 2021/12/2
     */
    @Transactional(readOnly = true)
    @Override
    public List<CompanyOrgMaintenanceTreeVO> getComOrgTreeDrl() throws ServiceBizException {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<CompanyOrgMaintenanceTreeVO> comOrgTree = organizationMapper.getComOrgTreeDrl(loginInfoDto.getAppId());

        return comOrgTree;
    }

    /**
     * 获取公司组织树
     *
     * @return java.util.List<java.util.Map>
     * @author zw
     * @since 2020/7/16
     */
    @Transactional(readOnly = true)
    @Override
    public List<CompanyOrgMaintenanceTreeVO> getComOrgTreeDistinct() throws ServiceBizException {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<CompanyOrgMaintenanceTreeVO> comOrgTree = organizationMapper.getComOrgTreeDistinct(loginInfoDto.getAppId(), loginInfoDto.getCompanyId());

        comOrgTree.stream().forEach(orgTree -> {
            if (StringUtils.isNullOrEmpty(orgTree.getParentOrgId())) {
                orgTree.setParent("#");
            }
        });
        return comOrgTree;
    }


    /**
     * 新增组织
     *
     * @param orgDto
     * @return java.lang.Integer
     * @author renwd
     * @since 2019/7/8
     */
    @Override
    public Integer addOrg(ComOrganizationDTO orgDto) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);

        QueryWrapper<ComOrganizationPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ComOrganizationPO::getOrgCode, orgDto.getOrgCode())
                .or().eq(ComOrganizationPO::getOrgName, orgDto.getOrgName());
        ComOrganizationPO comorganizationpo = organizationMapper.selectOne(queryWrapper);
        if (!StringUtils.isNullOrEmpty(comorganizationpo)) {
            throw new ServiceBizException("当前部门代码或名称已存在，请重新填写！");
        }

        ComOrganizationPO comorgpo = new ComOrganizationPO();
        comorgpo.setOrgType(orgDto.getOrgType());
        comorgpo.setBusiType(orgDto.getBusiType());
        comorgpo.setCompanyId(1);
        comorgpo.setOrgCode(orgDto.getOrgCode());
        comorgpo.setOrgName(orgDto.getOrgName());
        comorgpo.setParentOrgId(orgDto.getParentOrgId());
        comorgpo.setRemark(orgDto.getRemark());
        comorgpo.setStatus(orgDto.getStatus());
        comorgpo.setDealerCode(loginInfoDto.getOwnerCode());
        comorgpo.setAppId(loginInfoDto.getAppId());
        return organizationMapper.insert(comorgpo);
    }

    /**
     * 修改部门
     *
     * @param ids
     * @param orgDto
     * @return void
     * @author renwd
     * @since 2019/7/8
     */
    @Override
    public void modifyComOrg(String ids, ComOrganizationDTO orgDto) {
        // 如果无效
        if (SysAuthDictCodeConstants.STATUS_NOT_VALID == orgDto.getStatus()) {
            // 查询当前公司是否有下级
            QueryWrapper<ComOrganizationPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ComOrganizationPO::getParentOrgId, ids);
            List<ComOrganizationPO> organizationpos = organizationMapper.selectList(queryWrapper);
            if (!CommonUtils.isNullOrEmpty(organizationpos)) {
                throw new ServiceBizException("当前部门存在下级，不允许设为无效！");
            }
        }

        QueryWrapper<ComOrganizationPO> orgWrapper = new QueryWrapper<>();
        orgWrapper.lambda().eq(ComOrganizationPO::getOrgName, orgDto.getOrgName())
                .ne(ComOrganizationPO::getOrgId, ids);
        List<ComOrganizationPO> comorganizationpos = organizationMapper.selectList(orgWrapper);
        if (!CommonUtils.isNullOrEmpty(comorganizationpos)) {
            throw new ServiceBizException("当前部门名称已存在，请重新填写！");
        }

        ComOrganizationPO comorganizationpo = organizationMapper.selectById(ids);
        comorganizationpo.setOrgType(orgDto.getOrgType());
        comorganizationpo.setBusiType(orgDto.getBusiType());
        comorganizationpo.setOrgName(orgDto.getOrgName());
        comorganizationpo.setRemark(orgDto.getRemark());
        comorganizationpo.setStatus(orgDto.getStatus());
        organizationMapper.updateById(comorganizationpo);
    }


    /**
     * 保存公司表、经销商表、服务站表、组织表、组织关系表、
     * 人员表、用户表、员工表、职位表、角色表、app版本表、
     * 用户菜单表他的两个子表、员工菜单表以及他的两个子表。
     *
     * @return void
     * @author 李贺
     * @since 2019/9/10
     */
    @Override
    @Transactional
    public CompanyDealerAscVO addDealerCompany(CompanyDealerAscVO companyDealerAscVO) {

        LoginUserVO loginUserVO = companyDealerAscVO.getLoginUserVO();
        if (loginUserVO == null) {
            throw new ServiceBizException("loginUserVO不能为空");
        }
        //appId
        String appId = loginUserVO.getAppId();
        Long factoryCompanyId = companyMapper.findFactoryIdByAppId(appId);
        CompanyVO companyVO = companyDealerAscVO.getCompanyVO();

        if (factoryCompanyId == null) {
            throw new ServiceBizException("您输入的AppID可能不存在");
        }
        //保存公司
        String companyCode = companyVO.getCompanyCode();
        LambdaQueryWrapper<CompanyPO> lambdaQueryWrapper = new QueryWrapper<CompanyPO>().lambda();

        lambdaQueryWrapper.eq(CompanyPO::getCompanyCode, companyCode)
                .eq(CompanyPO::getAppId, appId);
        CompanyPO findcompanypo = companyMapper.selectOne(lambdaQueryWrapper);

        CompanyPO companypo = new CompanyPO();
        if (findcompanypo != null) {
            BeanMapperUtil.copyProperties(findcompanypo, companypo);
            BeanMapperUtil.copyProperties(companyVO, companypo);
            companyMapper.updateById(companypo);
        } else {
            BeanMapperUtil.copyProperties(companyVO, companypo);
            companypo.setIsDeleted(0);
            companypo.setOrgId(Integer.MAX_VALUE);
            companypo.setFactoryCompanyId(factoryCompanyId.intValue());
            companypo.setAppId(appId);
            companypo.setValidStatus(BaseDataDictConstants.IS_VALID);
            companypo.setCompanyType(ManageDictCodeConstants.ORG_TYPE_DEALER_COMPANY);
            companypo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
            companyMapper.insert(companypo);

            Integer companyId = companypo.getCompanyId();
            companyVO.setCompanyId(companyId);
            //保存组织
            OrgPO orgpo = new OrgPO();
            orgpo.setCompanyId(companyId.longValue());
            orgpo.setAppId(appId);
            orgpo.setOrgCode(companypo.getCompanyCode());
            orgpo.setOrgName(companypo.getCompanyNameCn());
            orgpo.setOrgShortName(companypo.getCompanyShortNameCn());
            orgpo.setOrgType(ManageDictCodeConstants.ORG_TYPE_DEALER_COMPANY);
            orgpo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
            orgpo.setIsValid(ManageDictCodeConstants.STATUS_IS_VALID);
            orgpo.setRecordVersion(0);
            orgpo.setOrgId(Long.MAX_VALUE);
            orgService.addOrg(orgpo);

            //保存组织关系
            TrOrgPO trorgpo = new TrOrgPO();
            trorgpo.setOrgId(orgpo.getOrgId());
            trorgpo.setParentOrgId(0L);
            orgService.addTrOrg(trorgpo);
            //更新公司
            companypo.setOrgId(orgpo.getOrgId().intValue());
            companyMapper.updateById(companypo);

            //保存人员信息
            //新增人员
            EmpPo empPo = new EmpPo();
            empPo.setAppId(appId);
            empPo.setUserCode(loginUserVO.getUserCode());
            empPo.setCompanyId(companyId);
            empPo.setMobilePhone(loginUserVO.getMobilePhone());
            empPo.setEmployeeName(loginUserVO.getUserCode());
            empPo.setIsOnjob(ManageDictCodeConstants.EMPLOYEE_ISJOB);
            empPo.setUserStatus(ManageDictCodeConstants.STATUS_QY);
            empPo.setDataSources(ManageDictCodeConstants.DATA_SOURCES_BY_OWNER);
            empService.addEmp(empPo);

            //保存员工信息
            EmployeePO employeepo = new EmployeePO();
            employeepo.setAppId(appId);
            employeepo.setCompanyId(companyId.longValue());
            employeepo.setEmpId(empPo.getEmpId());
            employeepo.setEmployeeNo(loginUserVO.getUserCode());
            employeepo.setOrgId(companypo.getOrgId().longValue());

            employeepo.setIsMajor(10041001);
            employeepo.setValidStatus(10041001);
            employeepo.setEmployeeStatus(10081001);
            employeepo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
            employeepo.setOwnerCode(companypo.getCompanyCode());
            employeeMapper.insert(employeepo);

            //新增用户
            UserPO userpo = new UserPO();
            userpo.setAppId(appId);
            userpo.setCompanyId(companyId.longValue());
            userpo.setEmpId(empPo.getEmpId().intValue());
            userpo.setUserCode(loginUserVO.getUserCode());
            userpo.setPassword(MD5Util.getEncryptedPwd(loginUserVO.getPassword()));
            userpo.setUserStatus(ManageDictCodeConstants.STATUS_QY);
            userpo.setFailureNum(0);
            userpo.setLockFlag(10041002);
            userpo.setIsDeleted(0);
            userService.addUser(userpo);
            loginUserVO.setUserId(userpo.getUserId());
            //查询模板role
            LambdaQueryWrapper<RolePO> lambdaQueryWrapper1 = new QueryWrapper<RolePO>().lambda();
            lambdaQueryWrapper1.eq(RolePO::getAppId, loginUserVO.getAppId())
                    .eq(RolePO::getDataType, ManageDictCodeConstants.DATA_TYPE_BY_OWNER)
                    .eq(RolePO::getRoleCode, loginUserVO.getRoleCode());
            RolePO rolepo = roleMapper.selectOne(lambdaQueryWrapper1);

            Long roleId = rolepo.getRoleId();

            //保存用户组织表
            UserOrgPO userorgpo = new UserOrgPO();
            userorgpo.setUserId(userpo.getUserId().longValue());
            userorgpo.setOrgId(companypo.getOrgId().longValue());
            userorgpo.setOwnerCode(companypo.getCompanyCode());
            userorgpo.setOwnerOrgType(ManageDictCodeConstants.ORG_TYPE_DEALER_COMPANY);
            userorgpo.setIsDeleted(0);

            userOrgMapper.insert(userorgpo);

            //保存组织角色表
            OrgRolePO orgrolepo = new OrgRolePO();
            orgrolepo.setRoleId(roleId);
            orgrolepo.setUserOrgId(userorgpo.getUserOrgId());
            orgrolepo.setRecordVersion(0);
            orgrolepo.setIsDeleted(0);
            orgRoleMapper.insert(orgrolepo);

            String createdBy = "0";
            //新增用户权限
            permissionMenuMapper.insertMenu(appId, userorgpo.getUserOrgId(), ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, roleId, ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE, createdBy);
            loginUserVO.setUserId(userpo.getUserId());
        }
        Integer companyId = companypo.getCompanyId();
        DealerInfoVO dealerInfoVO = companyDealerAscVO.getDealerInfoVO();
        if (dealerInfoVO != null) {

            if (StringUtils.isNullOrEmpty(dealerInfoVO.getDealerCode())) {
                throw new ServiceBizException("dealerCode不能为空");
            }

            LambdaQueryWrapper<DealerInfoPO> dealerInfoQuery = new QueryWrapper<DealerInfoPO>().lambda();
            dealerInfoQuery.eq(DealerInfoPO::getAppId, appId).eq(DealerInfoPO::getDealerCode, dealerInfoVO.getDealerCode());
            DealerInfoPO finddealerinfopo = dealerInfoMapper.selectOne(dealerInfoQuery);
            if (finddealerinfopo == null) {
                //新增经销商的组织
                OrgPO dealerinfoorgpo = new OrgPO();
                dealerinfoorgpo.setCompanyId(companyId.longValue());
                dealerinfoorgpo.setAppId(appId);
                dealerinfoorgpo.setOrgName(dealerInfoVO.getDealerName());
                dealerinfoorgpo.setOrgCode(dealerInfoVO.getDealerCode() + "DE");
                dealerinfoorgpo.setOrgShortName(dealerInfoVO.getDealerName());
                dealerinfoorgpo.setOrgType(ManageDictCodeConstants.ORG_TYPE_DEALER);
                dealerinfoorgpo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
                dealerinfoorgpo.setIsValid(ManageDictCodeConstants.STATUS_IS_VALID);
                dealerinfoorgpo.setRecordVersion(0);
                dealerinfoorgpo.setOrgId(Long.MAX_VALUE);
                orgService.addOrg(dealerinfoorgpo);

                DealerInfoPO dealerinfopo = new DealerInfoPO();
                BeanMapperUtil.copyProperties(dealerInfoVO, dealerinfopo);
                dealerinfopo.setCompanyId(companyId);
                dealerinfopo.setFactoryCompanyId(factoryCompanyId.intValue());
                dealerinfopo.setAppId(appId);
                dealerinfopo.setOrgType(ManageDictCodeConstants.ORG_TYPE_DEALER);
                dealerinfopo.setValidStatus(ManageDictCodeConstants.STATUS_IS_VALID);
                dealerinfopo.setStatus(BaseDataDictConstants.IS_VALID);
                dealerinfopo.setOrgId(dealerinfoorgpo.getOrgId().intValue());
                dealerInfoService.addDealerInfo(dealerinfopo);
                dealerInfoVO.setDealerInfoId(dealerinfopo.getDealerId());
                //保存经销商组织关系
                TrOrgPO dealerinfotrorgpo = new TrOrgPO();
                dealerinfotrorgpo.setOrgId(dealerinfoorgpo.getOrgId());
                dealerinfotrorgpo.setParentOrgId(companypo.getOrgId().longValue());
                orgService.addTrOrg(dealerinfotrorgpo);

                String saleArea = dealerInfoVO.getSaleArea();
                if (!StringUtils.isNullOrEmpty(saleArea)) {
                    TrOrgPO dealerinfotrorgpo2 = new TrOrgPO();
                    dealerinfotrorgpo2.setOrgId(dealerinfoorgpo.getOrgId());
                    List<Long> orgIdByCode = orgMapper.findOrgIdByCode(saleArea, factoryCompanyId.intValue());
                    if (orgIdByCode != null && orgIdByCode.size() > 0) {
                        dealerinfotrorgpo2.setParentOrgId(orgIdByCode.get(0));
                        orgService.addTrOrg(dealerinfotrorgpo2);

                        dealerinfopo.setSaleArea(orgIdByCode.get(0).toString());
                        dealerInfoMapper.updateById(dealerinfopo);
                    }
                }

            } else {
                BeanMapperUtil.copyProperties(dealerInfoVO, finddealerinfopo);
                dealerInfoMapper.updateById(finddealerinfopo);
                String saleArea = dealerInfoVO.getSaleArea();
                if (!StringUtils.isNullOrEmpty(saleArea)) {
                    TrOrgPO dealerinfotrorgpo2 = new TrOrgPO();
                    dealerinfotrorgpo2.setOrgId(finddealerinfopo.getOrgId().longValue());
                    List<Long> orgIdByCode = orgMapper.findOrgIdByCode(saleArea, factoryCompanyId.intValue());
                    if (orgIdByCode != null && orgIdByCode.size() > 0) {
                        //删除原有所属区域
                        List<Long> parentIds = trOrgMapper.findSaleArea(finddealerinfopo.getOrgId().longValue());
                        if (!CollectionUtils.isEmpty(parentIds)) {
                            trOrgMapper.deleteSaleArea(finddealerinfopo.getOrgId().longValue(), parentIds);
                        }
                        dealerinfotrorgpo2.setParentOrgId(orgIdByCode.get(0));
                        orgService.addTrOrg(dealerinfotrorgpo2);

                        finddealerinfopo.setSaleArea(orgIdByCode.get(0).toString());
                        dealerInfoMapper.updateById(finddealerinfopo);
                    }
                }
            }


        }

        AscInfoVO ascInfoVO = companyDealerAscVO.getAscInfoVO();
        if (ascInfoVO != null) {
            if (StringUtils.isNullOrEmpty(ascInfoVO.getAscCode())) {
                throw new ServiceBizException("ascCode不能为空");
            }
            LambdaQueryWrapper<AscInfoPO> ascinfopolambdaquerywrapper = new QueryWrapper<AscInfoPO>().lambda();
            ascinfopolambdaquerywrapper.eq(AscInfoPO::getAscCode, ascInfoVO.getAscCode())
                    .eq(AscInfoPO::getAppId, appId);

            AscInfoPO ascinfopo = ascInfoMapper.selectOne(ascinfopolambdaquerywrapper);
            if (ascinfopo == null) {
                //保存服务站组织信息
                OrgPO ascinfoorgpo = new OrgPO();
                ascinfoorgpo.setCompanyId(companyId.longValue());
                ascinfoorgpo.setAppId(appId);
                ascinfoorgpo.setOrgName(ascInfoVO.getAscName());
                ascinfoorgpo.setOrgShortName(ascInfoVO.getAscName());
                ascinfoorgpo.setOrgCode(ascInfoVO.getAscCode() + "AS");
                ascinfoorgpo.setOrgShortName(ascInfoVO.getAscName());
                ascinfoorgpo.setOrgType(ManageDictCodeConstants.ORG_TYPE_ASC);
                ascinfoorgpo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
                ascinfoorgpo.setIsValid(ManageDictCodeConstants.STATUS_IS_VALID);
                ascinfoorgpo.setRecordVersion(0);
                ascinfoorgpo.setOrgId(Long.MAX_VALUE);
                orgService.addOrg(ascinfoorgpo);

                //保存服务站信息
                ascinfopo = new AscInfoPO();
                BeanMapperUtil.copyProperties(ascInfoVO, ascinfopo);
                ascinfopo.setAscCode(ascInfoVO.getAscCode());
                ascinfopo.setAscName(ascInfoVO.getAscName());
                ascinfopo.setOrgId(ascinfoorgpo.getOrgId().intValue());
                ascinfopo.setAppId(appId);
                ascinfopo.setCompanyId(companyId);
                ascinfopo.setFactoryCompanyId(factoryCompanyId.intValue());
                ascinfopo.setOrgType(ManageDictCodeConstants.ORG_TYPE_ASC);
                ascinfopo.setValidStatus(BaseDataDictConstants.IS_VALID);
                ascinfoorgpo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
                ascInfoService.addAscInfo(ascinfopo);
                ascInfoVO.setAscInfoId(ascinfopo.getAscId());
                //保存服务站组织关系信息
                TrOrgPO ascinfotrorgpo = new TrOrgPO();
                ascinfotrorgpo.setOrgId(ascinfoorgpo.getOrgId());
                ascinfotrorgpo.setParentOrgId(ascinfoorgpo.getOrgId());
                ascinfotrorgpo.setParentOrgId(companypo.getOrgId().longValue());
                orgService.addTrOrg(ascinfotrorgpo);

                String ascArea = ascInfoVO.getAscArea();
                if (!StringUtils.isNullOrEmpty(ascArea)) {
                    TrOrgPO ascinfotrorgpo2 = new TrOrgPO();
                    ascinfotrorgpo2.setOrgId(ascinfopo.getOrgId().longValue());
                    List<Long> orgIdByCode = orgMapper.findOrgIdByCode(ascArea, factoryCompanyId.intValue());
                    if (orgIdByCode != null && orgIdByCode.size() > 0) {
                        ascinfotrorgpo2.setParentOrgId(orgIdByCode.get(0));
                        orgService.addTrOrg(ascinfotrorgpo2);

                        ascinfopo.setAscArea(orgIdByCode.get(0).intValue());
                        ascInfoMapper.updateById(ascinfopo);
                    }
                }
            } else {
                BeanMapperUtil.copyProperties(ascInfoVO, ascinfopo);
                ascInfoMapper.updateById(ascinfopo);

                String ascArea = ascInfoVO.getAscArea();
                if (!StringUtils.isNullOrEmpty(ascArea)) {
                    TrOrgPO ascinfotrorgpo2 = new TrOrgPO();
                    ascinfotrorgpo2.setOrgId(ascinfopo.getOrgId().longValue());
                    List<Long> orgIdByCode = orgMapper.findOrgIdByCode(ascArea, factoryCompanyId.intValue());
                    if (orgIdByCode != null && orgIdByCode.size() > 0) {
                        //删除原有所属区域
                        List<Long> parentIds = trOrgMapper.findSaleArea(ascinfopo.getOrgId().longValue());
                        if (!CollectionUtils.isEmpty(parentIds)) {
                            trOrgMapper.deleteSaleArea(ascinfopo.getOrgId().longValue(), parentIds);
                        }
                        ascinfotrorgpo2.setParentOrgId(orgIdByCode.get(0));
                        orgService.addTrOrg(ascinfotrorgpo2);

                        ascinfopo.setAscArea(orgIdByCode.get(0).intValue());
                        ascInfoMapper.updateById(ascinfopo);
                    }
                }
            }

        }

        if (dealerInfoVO != null && !StringUtils.isNullOrEmpty(dealerInfoVO.getDealerCode())) {
            String ownerCode = dealerInfoVO.getDealerCode();
            Map<String, Object> data = new HashMap<>();
            data.put("appId", appId);
            data.put("ownerCode", ownerCode);
            data.put("ownerParCode", ownerCode);
            data.put("companyCode", companypo.getCompanyCode());
            data.put("orgId", "");
            //远程调用对象：url / body参数（json）/  header
            MessEvent messEvent = new MessEvent();
            String channel = "sysParam";
            messEvent.setUrl("http://OPS-NOTIFY/notify/invoke/message?channel=" + channel);
            messEvent.setParam(data);
            messEvent.setHeaders(null);
            //远程调用
            iRemoteInvoke.sendPostWithTransaction(messEvent);
        }

        return companyDealerAscVO;
    }

    /**
     * 新增多个公司
     *
     * @author 李贺
     * @since 2019/12/2
     */
    @Override
    public List<CompanyDealerAscVO> addDealerCompanyList(List<CompanyDealerAscVO> companyDealerAscVOList) {
        ArrayList<CompanyDealerAscVO> companydealerascvos = new ArrayList<>();
        for (CompanyDealerAscVO companyDealerAscVO : companyDealerAscVOList) {
            companydealerascvos.add(addDealerCompany(companyDealerAscVO));
        }
        return companydealerascvos;
    }

    /**
     * 更新公司表
     *
     * @author 李贺
     * @since 2019/9/12
     */
    @Override
    @Transactional
    public CompanyDealerAscVO updateCompany(CompanyDealerAscVO companyDealerAscVO) {

        LoginUserVO loginUserVO = companyDealerAscVO.getLoginUserVO();
        if (loginUserVO == null) {
            throw new ServiceBizException("loginUserVO不能为空");
        }
        loginUserVO.setUserId(null);
        String appId = loginUserVO.getAppId();
        if (StringUtils.isNullOrEmpty(appId)) {
            throw new ServiceBizException("loginUserVO中appId不能为空");
        }
        String oldUserCode = loginUserVO.getOldUserCode();
        if (StringUtils.isNullOrEmpty(oldUserCode)) {
            throw new ServiceBizException("loginUserVO中oldUserCode不能为空");
        }
        CompanyPO companypo = new CompanyPO();

        LambdaQueryWrapper<UserPO> lambdaQueryWrapper = new QueryWrapper<UserPO>().lambda();
        lambdaQueryWrapper.eq(UserPO::getUserCode, oldUserCode)
                .eq(UserPO::getAppId, appId);
        UserPO userpo = userMapper.selectOne(lambdaQueryWrapper);
        Object jwt = redisClient.get(userpo.getUserId().toString());
        if (!StringUtils.isNullOrEmpty(jwt)) {
            redisClient.del(userpo.getUserId().toString());
            redisClient.del((String) jwt);

            redisClient.hdel("cyxdms:sysAuth:user:10041001", userpo.getUserId().toString());
            redisClient.hdel("cyxdms:sysAuth:user:10041002", userpo.getUserId().toString());
        }
        Object pcjwt = redisClient.get(userpo.getUserId().toString() + SysAuthCommonConstants.JWT_CLIENT_DELIMITER + SysAuthCommonConstants.JWT_CLIENT_LOGINWAY_PC);
        if (!StringUtils.isNullOrEmpty(pcjwt)) {
            redisClient.del(userpo.getUserId().toString() + SysAuthCommonConstants.JWT_CLIENT_DELIMITER + SysAuthCommonConstants.JWT_CLIENT_LOGINWAY_PC);
            redisClient.del((String) pcjwt);

            redisClient.hdel("cyxdms:sysAuth:user:10041001", userpo.getUserId().toString());
            redisClient.hdel("cyxdms:sysAuth:user:10041002", userpo.getUserId().toString());
        }
        Object appjwt = redisClient.get(userpo.getUserId().toString() + SysAuthCommonConstants.JWT_CLIENT_DELIMITER + SysAuthCommonConstants.JWT_CLIENT_LOGINWAY_APP);
        if (!StringUtils.isNullOrEmpty(appjwt)) {
            redisClient.del(userpo.getUserId().toString() + SysAuthCommonConstants.JWT_CLIENT_DELIMITER + SysAuthCommonConstants.JWT_CLIENT_LOGINWAY_APP);
            redisClient.del((String) appjwt);
            redisClient.hdel("cyxdms:sysAuth:user:10041001", userpo.getUserId().toString());
            redisClient.hdel("cyxdms:sysAuth:user:10041002", userpo.getUserId().toString());
        }
        //更新公司
        CompanyVO companyVO = companyDealerAscVO.getCompanyVO();
        Long factoryId = companyMapper.findFactoryIdByAppId(appId);
        if (companyVO != null) {
            companyVO.setCompanyId(null);
            CompanyPO companypo1 = new CompanyPO();
            BeanMapperUtil.copyProperties(companyVO, companypo1);
            String oldCompanyCode = companyVO.getOldCompanyCode();
            if (StringUtils.isNullOrEmpty(oldCompanyCode)) {
                throw new ServiceBizException("修改公司时oldCompanyCode不能为空");
            }
            LambdaQueryWrapper<CompanyPO> poLambdaQueryWrapper = new QueryWrapper<CompanyPO>().lambda();

            poLambdaQueryWrapper.eq(CompanyPO::getCompanyCode, oldCompanyCode)
                    .eq(CompanyPO::getAppId, appId);
            companypo = companyMapper.selectOne(poLambdaQueryWrapper);
            if (companypo == null) {
                throw new ServiceBizException("更新公司时oldCompanyCode错误");
            }
            CompanyPO companypo2 = BeanMapperUtil.copyProperties(companyDealerAscVO.getCompanyVO(), CompanyPO.class);
            BeanMapperUtil.copyPropertiesWithOutNull(companypo2, companypo);
            companyMapper.updateById(companypo);
            companyVO.setCompanyId(companypo.getCompanyId());

            Integer orgId = companypo.getOrgId();

            OrgPO orgpo = orgMapper.selectById(orgId);
            orgpo.setOrgCode(companypo.getCompanyCode());
            orgpo.setOrgName(companypo.getCompanyNameCn());
            orgpo.setOrgShortName(companypo.getCompanyShortNameCn());
            orgMapper.updateById(orgpo);

            employeeMapper.updateOwnerCode(companypo.getCompanyCode(), oldUserCode, appId);
        }


        DealerInfoVO dealerInfoVO = companyDealerAscVO.getDealerInfoVO();
        DealerInfoPO dealerinfopo = new DealerInfoPO();
        if (dealerInfoVO != null) {
            dealerInfoVO.setDealerInfoId(null);
            String oldDealerCode = dealerInfoVO.getOldDealerCode();
            if (StringUtils.isNullOrEmpty(dealerInfoVO.getDealerCode())) {
                throw new ServiceBizException("dealerCode不能为空");
            }
            if (StringUtils.isNullOrEmpty(oldDealerCode)) {

                //新增经销商的组织
                OrgPO dealerinfoorgpo = new OrgPO();
                dealerinfoorgpo.setCompanyId(companypo.getCompanyId().longValue());
                dealerinfoorgpo.setAppId(appId);
                dealerinfoorgpo.setOrgName(dealerInfoVO.getDealerName());
                dealerinfoorgpo.setOrgCode(dealerInfoVO.getDealerCode() + "DE");
                dealerinfoorgpo.setOrgShortName(dealerInfoVO.getDealerName());
                dealerinfoorgpo.setOrgType(ManageDictCodeConstants.ORG_TYPE_DEALER);
                dealerinfoorgpo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
                dealerinfoorgpo.setIsValid(ManageDictCodeConstants.STATUS_IS_VALID);
                dealerinfoorgpo.setRecordVersion(0);
                dealerinfoorgpo.setOrgId(Long.MAX_VALUE);
                orgService.addOrg(dealerinfoorgpo);


                BeanMapperUtil.copyProperties(dealerInfoVO, dealerinfopo);
                dealerinfopo.setCompanyId(companypo.getCompanyId());
                dealerinfopo.setFactoryCompanyId(companypo.getFactoryCompanyId());
                dealerinfopo.setAppId(appId);
                dealerinfopo.setOrgType(ManageDictCodeConstants.ORG_TYPE_DEALER);
                dealerinfopo.setValidStatus(ManageDictCodeConstants.STATUS_IS_VALID);
                dealerinfopo.setStatus(BaseDataDictConstants.IS_VALID);
                dealerinfopo.setOrgId(dealerinfoorgpo.getOrgId().intValue());
                dealerInfoService.addDealerInfo(dealerinfopo);

                //保存经销商组织关系
                TrOrgPO dealerinfotrorgpo = new TrOrgPO();
                dealerinfotrorgpo.setOrgId(dealerinfopo.getOrgId().longValue());
                dealerinfotrorgpo.setParentOrgId(companypo.getOrgId().longValue());
                orgService.addTrOrg(dealerinfotrorgpo);
                Long factoryCompanyId = companyMapper.findFactoryIdByAppId(appId);
                //保存经销商与事业部组织关系
                String saleArea = dealerInfoVO.getSaleArea();
                if (!StringUtils.isNullOrEmpty(saleArea)) {
                    TrOrgPO dealerinfotrorgpo2 = new TrOrgPO();
                    dealerinfotrorgpo2.setOrgId(dealerinfopo.getOrgId().longValue());
                    List<Long> orgIdByCode = orgMapper.findOrgIdByCode(saleArea, factoryCompanyId.intValue());
                    if (orgIdByCode != null && orgIdByCode.size() > 0) {
                        dealerinfotrorgpo2.setParentOrgId(orgIdByCode.get(0));
                        orgService.addTrOrg(dealerinfotrorgpo2);

                        dealerinfopo.setSaleArea(orgIdByCode.get(0).toString());
                        dealerInfoMapper.updateById(dealerinfopo);
                    }
                }

            } else {
                //更新经销商
                DealerInfoPO dealerinfopo1 = new DealerInfoPO();

                BeanMapperUtil.copyProperties(dealerInfoVO, dealerinfopo1);

                LambdaQueryWrapper<DealerInfoPO> dealerInfoQuery = new QueryWrapper<DealerInfoPO>().lambda();
                dealerInfoQuery.eq(DealerInfoPO::getAppId, appId).eq(DealerInfoPO::getDealerCode, oldDealerCode);
                dealerinfopo = dealerInfoMapper.selectOne(dealerInfoQuery);
                if (dealerinfopo == null) {
                    throw new ServiceBizException("更新经销商时oldDelerCode错误");
                }

                DealerInfoPO dealerinfopo2 = BeanMapperUtil.copyProperties(companyDealerAscVO.getDealerInfoVO(), DealerInfoPO.class);
                BeanMapperUtil.copyPropertiesWithOutNull(dealerinfopo2, dealerinfopo);

                dealerInfoMapper.updateById(dealerinfopo);

                OrgPO orgpo = orgMapper.selectById(dealerinfopo.getOrgId());
                orgpo.setOrgName(dealerInfoVO.getDealerName());
                orgpo.setOrgCode(dealerInfoVO.getDealerCode() + "DE");
                orgpo.setOrgShortName(dealerInfoVO.getDealerName());
                orgMapper.updateById(orgpo);
                Long factoryCompanyId = companyMapper.findFactoryIdByAppId(appId);
                //保存经销商与事业部组织关系
                String saleArea = dealerInfoVO.getSaleArea();
                if (!StringUtils.isNullOrEmpty(saleArea)) {
                    TrOrgPO dealerinfotrorgpo2 = new TrOrgPO();
                    dealerinfotrorgpo2.setOrgId(dealerinfopo.getOrgId().longValue());
                    List<Long> orgIdByCode = orgMapper.findOrgIdByCode(saleArea, factoryCompanyId.intValue());
                    if (orgIdByCode != null && orgIdByCode.size() > 0) {
                        //删除原有所属区域
                        List<Long> parentIds = trOrgMapper.findSaleArea(dealerinfopo.getOrgId().longValue());
                        if (!CollectionUtils.isEmpty(parentIds)) {
                            trOrgMapper.deleteSaleArea(dealerinfopo.getOrgId().longValue(), parentIds);
                        }
                        dealerinfotrorgpo2.setParentOrgId(orgIdByCode.get(0));
                        orgService.addTrOrg(dealerinfotrorgpo2);

                        dealerinfopo.setSaleArea(orgIdByCode.get(0).toString());
                        dealerInfoMapper.updateById(dealerinfopo);
                    }
                }
            }
            dealerInfoVO.setDealerInfoId(dealerinfopo.getDealerId());

        }

        //更新asc
        AscInfoVO ascInfoVO = companyDealerAscVO.getAscInfoVO();

        AscInfoPO ascinfopo = new AscInfoPO();
        if (ascInfoVO != null) {
            ascInfoVO.setAscInfoId(null);
            String oldAscCode = ascInfoVO.getOldAscCode();
            if (StringUtils.isNullOrEmpty(oldAscCode)) {

                if (StringUtils.isNullOrEmpty(ascInfoVO.getAscCode())) {
                    throw new ServiceBizException("ascCode不能为空");
                }

                //保存服务站组织信息
                OrgPO ascinfoorgpo = new OrgPO();
                ascinfoorgpo.setCompanyId(companypo.getCompanyId().longValue());
                ascinfoorgpo.setAppId(appId);
                ascinfoorgpo.setOrgName(ascInfoVO.getAscName());
                ascinfoorgpo.setOrgShortName(ascInfoVO.getAscName());
                ascinfoorgpo.setOrgCode(ascInfoVO.getAscCode() + "AS");
                ascinfoorgpo.setOrgShortName(ascInfoVO.getAscName());
                ascinfoorgpo.setOrgType(ManageDictCodeConstants.ORG_TYPE_ASC);
                ascinfoorgpo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
                ascinfoorgpo.setIsValid(ManageDictCodeConstants.STATUS_IS_VALID);
                ascinfoorgpo.setRecordVersion(0);
                ascinfoorgpo.setOrgId(Long.MAX_VALUE);
                orgService.addOrg(ascinfoorgpo);

                //保存服务站信息
                BeanMapperUtil.copyProperties(ascInfoVO, ascinfopo);
                ascinfopo.setAscCode(ascInfoVO.getAscCode());
                ascinfopo.setAscName(ascInfoVO.getAscName());
                ascinfopo.setOrgId(ascinfoorgpo.getOrgId().intValue());
                ascinfopo.setAppId(appId);
                ascinfopo.setCompanyId(companypo.getCompanyId());
                ascinfopo.setFactoryCompanyId(companypo.getFactoryCompanyId());
                ascinfopo.setOrgType(ManageDictCodeConstants.ORG_TYPE_ASC);
                ascinfopo.setValidStatus(BaseDataDictConstants.IS_VALID);
                ascinfoorgpo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
                ascInfoService.addAscInfo(ascinfopo);

                //保存服务站组织关系信息
                TrOrgPO ascinfotrorgpo = new TrOrgPO();
                ascinfotrorgpo.setOrgId(ascinfoorgpo.getOrgId());
                ascinfotrorgpo.setParentOrgId(ascinfoorgpo.getOrgId());
                ascinfotrorgpo.setParentOrgId(companypo.getOrgId().longValue());
                orgService.addTrOrg(ascinfotrorgpo);

                String ascArea = ascInfoVO.getAscArea();
                if (!StringUtils.isNullOrEmpty(ascArea)) {
                    TrOrgPO ascinfotrorgpo2 = new TrOrgPO();
                    ascinfotrorgpo2.setOrgId(ascinfopo.getOrgId().longValue());

                    List<Long> orgIdByCode = orgMapper.findOrgIdByCode(ascArea, factoryId.intValue());
                    if (orgIdByCode != null && orgIdByCode.size() > 0) {
                        //删除原有所属区域
                        List<Long> parentIds = trOrgMapper.findSaleArea(ascinfopo.getOrgId().longValue());
                        if (!CollectionUtils.isEmpty(parentIds)) {
                            trOrgMapper.deleteSaleArea(ascinfopo.getOrgId().longValue(), parentIds);
                        }
                        ascinfotrorgpo2.setParentOrgId(orgIdByCode.get(0));
                        orgService.addTrOrg(ascinfotrorgpo2);

                        ascinfopo.setAscArea(orgIdByCode.get(0).intValue());
                        ascInfoMapper.updateById(ascinfopo);
                    }
                }

            } else {
                AscInfoPO ascinfopo1 = new AscInfoPO();
                BeanMapperUtil.copyProperties(companyDealerAscVO.getAscInfoVO(), ascinfopo1);

                LambdaQueryWrapper<AscInfoPO> poLambdaQueryWrapper = new QueryWrapper<AscInfoPO>().lambda();
                poLambdaQueryWrapper.eq(AscInfoPO::getAscCode, ascInfoVO.getOldAscCode())
                        .eq(AscInfoPO::getAppId, appId);

                ascinfopo = ascInfoMapper.selectOne(poLambdaQueryWrapper);
                if (ascinfopo == null) {
                    throw new ServiceBizException("更新asc时oldAscCode错误");
                }
                AscInfoPO ascinfopo2 = BeanMapperUtil.copyProperties(companyDealerAscVO.getAscInfoVO(), AscInfoPO.class);
                BeanMapperUtil.copyPropertiesWithOutNull(ascinfopo2, ascinfopo);
                ascInfoService.updateAscById(ascinfopo);


                OrgPO orgpo = orgMapper.selectById(ascinfopo.getOrgId());
                orgpo.setOrgName(ascinfopo.getAscName());
                orgpo.setOrgCode(ascinfopo.getAscCode() + "AS");
                orgpo.setOrgShortName(ascinfopo.getAscShortName());
                orgMapper.updateById(orgpo);

                String ascArea = ascInfoVO.getAscArea();
                if (!StringUtils.isNullOrEmpty(ascArea)) {
                    TrOrgPO ascinfotrorgpo2 = new TrOrgPO();
                    ascinfotrorgpo2.setOrgId(ascinfopo.getOrgId().longValue());

                    List<Long> orgIdByCode = orgMapper.findOrgIdByCode(ascArea, factoryId.intValue());
                    if (orgIdByCode != null && orgIdByCode.size() > 0) {
                        ascinfotrorgpo2.setParentOrgId(orgIdByCode.get(0));
                        orgService.addTrOrg(ascinfotrorgpo2);

                        ascinfopo.setAscArea(orgIdByCode.get(0).intValue());
                        ascInfoMapper.updateById(ascinfopo);
                    }
                }


            }
            ascInfoVO.setAscInfoId(ascinfopo.getAscId());
        }

        userpo.setUserCode(loginUserVO.getUserCode());
        userpo.setPassword(MD5Util.getEncryptedPwd(loginUserVO.getPassword()));
        userMapper.updateById(userpo);

        QueryWrapper<UserOrgPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userpo.getUserId());
        List<UserOrgPO> userorgpos1 = userOrgMapper.selectList(queryWrapper);
        for (UserOrgPO userorgpo : userorgpos1) {
            userorgpo.setOwnerCode(companypo.getCompanyCode());
            Long ownerId = orgMapper.getOwnerIdByOrgId(companypo.getOrgId().longValue());
            if (!StringUtils.isNullOrEmpty(ownerId)) {
                OrgPO orgpo = orgMapper.selectById(ownerId);
                userorgpo.setOwnerOrgType(orgpo.getOrgType());
            }
            userOrgMapper.updateById(userorgpo);
        }
        EmpPo empPo = empMapper.selectById(userpo.getEmpId());
        empPo.setUserCode(userpo.getUserCode());
        if (StringUtils.isNullOrEmpty(loginUserVO.getMobilePhone())) {
        } else {
            empPo.setMobilePhone(loginUserVO.getMobilePhone());
        }
        empPo.setEmployeeName(userpo.getUserCode());
        empPo.setUserCode(userpo.getUserCode());
        empMapper.updateById(empPo);

        LambdaQueryWrapper<EmployeePO> lambdaQueryWrapper1 = new QueryWrapper<EmployeePO>().lambda();
        lambdaQueryWrapper1.eq(EmployeePO::getEmpId, empPo.getEmpId())
                .eq(EmployeePO::getAppId, appId);
        EmployeePO employeepo = employeeMapper.selectOne(lambdaQueryWrapper1);
        employeepo.setEmployeeNo(loginUserVO.getUserCode());
        employeepo.setOwnerCode(companypo.getCompanyCode());
        employeeMapper.updateById(employeepo);

        Integer userId1 = userpo.getUserId();

        LambdaQueryWrapper<UserOrgPO> userorgpolambdaquerywrapper = new QueryWrapper<UserOrgPO>().lambda();
        userorgpolambdaquerywrapper.eq(UserOrgPO::getUserId, userId1);
        List<UserOrgPO> userorgpos = userOrgMapper.selectList(userorgpolambdaquerywrapper);
        List<Long> userOrgIds = userorgpos.stream().map(UserOrgPO::getUserOrgId).collect(Collectors.toList());

        if (userOrgIds.size() != 0) {
            permissionMenuMapper.deletePermissionMenusByPerIds(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userOrgIds);
        }

        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Long userId = loginInfoDto.getUserId();
        String createdBy;
        if (userId == null) {
            createdBy = "0";
        } else {
            createdBy = userId.toString();
        }

        //查询模板role
        LambdaQueryWrapper<RolePO> poLambdaQueryWrapper = new QueryWrapper<RolePO>().lambda();
        poLambdaQueryWrapper.eq(RolePO::getAppId, loginUserVO.getAppId())
                .eq(RolePO::getDataType, ManageDictCodeConstants.DATA_TYPE_BY_OWNER)
                .eq(RolePO::getRoleCode, loginUserVO.getRoleCode());
        RolePO rolepo = roleMapper.selectOne(poLambdaQueryWrapper);

        Long roleId = rolepo.getRoleId();

        LambdaQueryWrapper<OrgRolePO> poLambdaQueryWrapper1 = new QueryWrapper<OrgRolePO>().lambda();
        poLambdaQueryWrapper1.eq(OrgRolePO::getUserOrgId, userOrgIds.get(0));
        OrgRolePO orgrolepo = orgRoleMapper.selectOne(poLambdaQueryWrapper1);
        orgrolepo.setRoleId(roleId);
        orgRoleMapper.updateById(orgrolepo);

        //新增用户权限
        permissionMenuMapper.insertMenu(appId, userOrgIds.get(0), ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, roleId, ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE, createdBy);

        loginUserVO.setUserId(userpo.getUserId());

        //add
        if (dealerInfoVO != null && !StringUtils.isNullOrEmpty(dealerInfoVO.getDealerCode())) {
            String ownerCode = dealerInfoVO.getDealerCode();
            Map<String, Object> data = new HashMap<>();
            data.put("appId", appId);
            data.put("ownerCode", ownerCode);
            data.put("ownerParCode", ownerCode);
            data.put("companyCode", companypo.getCompanyCode());
            data.put("orgId", "");
            //远程调用对象：url / body参数（json）/  header
            MessEvent messEvent = new MessEvent();
            String channel = "sysParam";
            messEvent.setUrl("http://OPS-NOTIFY/notify/invoke/message?channel=" + channel);
            messEvent.setParam(data);
            messEvent.setHeaders(null);
            //远程调用
            iRemoteInvoke.sendPostWithTransaction(messEvent);
        }
        return companyDealerAscVO;
    }

    /**
     * 根据公司Id,获得公司信息
     * <p>
     * *@author 李贺
     *
     * @since 2019/10/18
     */
    @Override
    public CompanyVO getCompany(Long companyId) {
        CompanyVO companyVO = new CompanyVO();
        BeanUtils.copyProperties(companyVO, companyMapper.selectById(companyId));
        return companyVO;
    }

    @Override
    public MergeVO getMerge() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String appId = loginInfoDto.getAppId();
        MergeVO mergeVO = companyMapper.getFactoryCom(appId);
        if (mergeVO == null) {
            mergeVO = new MergeVO();
        }
        if (mergeVO.getIsDisArea() == null) {
            mergeVO.setIsDisArea(10041002L);
        }
        if (mergeVO.getIsMerge() == null) {
            mergeVO.setIsMerge(10041002L);
        }
        return mergeVO;
    }

    /**
     * 获得当前车厂的信息
     *
     * @return: 获得当前车厂的信息
     * @auther: 李贺
     * @since: 2019/11/26
     */
    @Override
    public CompanyVO factoryCompany() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<CompanyPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_id", loginInfoDto.getAppId()).eq("COMPANY_TYPE", ManageDictCodeConstants.ORG_TYPE_FACTORY);
        CompanyPO companypo = companyMapper.selectOne(queryWrapper);
        return BeanMapperUtil.copyProperties(companypo, CompanyVO.class);
    }

    /**
     * 根据公司统一社会信息用代码匹配SAP客户编号
     *
     * @param credentialsNo 证件号（统一社会信用代码）
     * @return
     */
    @Override
    public List<String> matchingSapCustomerNo(String credentialsNo) {
        if (StringUtils.isBlank(credentialsNo)) {
            return null;
        }
        List<String> companyCodeList = companyMapper.matchingSapCustomerNo(credentialsNo);
        return companyCodeList;
    }
}
